<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="admin.Connectmysql" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>考试列表</title>
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", sans-serif;
        }

        body {
            background: #f5f7fa;
            padding: 20px;
        }

        /* 标题样式 */
        .page-title {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin-bottom: 20px;
            border-left: 5px solid #007bff;
            padding-left: 10px;
        }

        /* 卡片容器：CSS 网格实现响应式布局 */
        .exam-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            grid-gap: 20px;
        }

        /* 考试卡片样式 */
        .exam-card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            padding: 20px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            transition: transform 0.3s ease;
        }

        .exam-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        /* 卡片标题 */
        .exam-card h3 {
            font-size: 18px;
            color: #333;
            margin-bottom: 12px;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        /* 信息项样式 */
        .exam-info {
            color: #666;
            font-size: 14px;
            line-height: 1.8;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }

        /* 图标样式（可替换为实际图标字体） */
        .exam-info::before {
            content: "";
            width: 16px;
            height: 16px;
            margin-right: 6px;
            background: url('data:image/svg+xml;utf8,<svg fill="%23666" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm1-12h-2v6h2v-6zm0 4h-2v2h2v-2z"/></svg>') no-repeat center;
            background-size: contain;
        }

        /* 倒计时样式 */
        .countdown {
            margin: 10px 0;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 500;
            text-align: center;
        }

        .countdown-upcoming {
            background: #fff3cd;
            color: #856404;
        }

        .countdown-active {
            background: #d4edda;
            color: #155724;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(64, 192, 87, 0.4);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(64, 192, 87, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(64, 192, 87, 0);
            }
        }

        .countdown-expired {
            background: #f8d7da;
            color: #721c24;
        }

        /* 状态标签 */
        .status-tag {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: #fff;
            margin-left: 10px;
        }

        .status-upcoming {
            background: #ffc107;
        }

        .status-exam {
            background: #40c057;
        }

        .status-finished {
            background: #dc3545;
        }

        .status-graded {
            background: #6c757d;
        }

        /* 操作按钮 */
        .btn-take {
            display: inline-block;
            margin-top: 10px;
            padding: 8px 16px;
            background: #007bff;
            color: #fff;
            text-decoration: none;
            border-radius: 4px;
            align-self: flex-start;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .btn-take:hover {
            background: #0056b3;
            transform: translateY(-1px);
            box-shadow: 0 2px 6px rgba(0,0,0,0.2);
        }

        .btn-disabled {
            background: #e9ecef;
            color: #6c757d;
            cursor: not-allowed;
            pointer-events: none;
        }

        /* 响应式适配 */
        @media (max-width: 768px) {
            .exam-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
<h2 class="page-title">考试列表</h2>

<div class="exam-grid">
    <%
        try {
            ResultSet rs = null;
            Connectmysql cmysql = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver");
            String sql = "SELECT id, name, course, teacher, date, duration, status FROM exam1";
            cmysql.open();
            rs = cmysql.executeSql(sql,new Object[]{});

            while (rs.next()) {
                int id = rs.getInt("id");
                String examName = rs.getString("name");
                String course = rs.getString("course");
                String teacher = rs.getString("teacher");
                Timestamp examDate = rs.getTimestamp("date");
                int duration = rs.getInt("duration");
                int status = rs.getInt("status"); // 假设status字段区分状态
//                int graded = rs.getInt("graded"); // 是否已阅卷
    %>
    <div class="exam-card" data-exam-id="<%= id %>">
        <h3><%= examName %></h3>

        <div class="exam-info">
            课程：<%= course %>
        </div>
        <div class="exam-info">
            出题教师：<%= teacher %>
        </div>
        <div class="exam-info">
            开考时间：<%= examDate %>
        </div>
        <div class="exam-info">
            考试时长：<%= duration %> 分钟
        </div>

        <!-- 状态标签和倒计时容器 -->
        <div id="status-<%= id %>" class="status-container">
            <!-- 状态标签由JavaScript动态生成 -->
        </div>

        <div id="countdown-<%= id %>" class="countdown">
            <!-- 倒计时由JavaScript动态生成 -->
        </div>

        <!-- 跳转按钮 -->
        <a id="btn-<%= id %>" class="btn-take" href="takeExam.jsp?exam=<%= id %>">
            进入考试
        </a>
    </div>
    <%
            }
            cmysql.close();
        } catch (ClassNotFoundException f) {
            f.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            out.println("<div style='color:red; padding:20px;'>数据库连接错误，请稍后再试！</div>");
        }
    %>
</div>

<script>
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 获取所有考试卡片
        const examCards = document.querySelectorAll('.exam-card');

        // 初始化所有考试的倒计时
        examCards.forEach(card => {
            const examId = card.getAttribute('data-exam-id');
            updateExamStatus(examId);
        });

        // 每秒更新一次倒计时
        setInterval(() => {
            examCards.forEach(card => {
                const examId = card.getAttribute('data-exam-id');
                updateExamStatus(examId);
            });
        }, 1000);
    });

    // 更新考试状态和倒计时
    function updateExamStatus(examId) {
        // 获取考试卡片元素
        const card = document.querySelector(`.exam-card[data-exam-id="${examId}"]`);
        if (!card) return;

        // 获取考试开始时间（从页面元素或其他数据源获取）
        // 注意：这里需要从服务器获取实际的考试时间，目前使用模拟数据
        // 实际应用中，应该从服务器获取考试时间戳并传递到前端
        const examDateStr = card.querySelector('.exam-info:nth-child(4)').textContent.trim().split('：')[1];
        const examDate = new Date(examDateStr);

        // 获取考试时长（分钟）
        const durationStr = card.querySelector('.exam-info:nth-child(5)').textContent.trim().split('：')[1];
        const durationMinutes = parseInt(durationStr);
        const durationMillis = durationMinutes * 60 * 1000;

        // 计算考试结束时间
        const endDate = new Date(examDate.getTime() + durationMillis);

        // 获取当前时间
        const now = new Date();

        // 获取状态和倒计时元素
        const statusElement = document.getElementById(`status-${examId}`);
        const countdownElement = document.getElementById(`countdown-${examId}`);
        const btnElement = document.getElementById(`btn-${examId}`);

        if (!statusElement || !countdownElement || !btnElement) return;

        // 计算时间差
        let timeDiff;
        let statusHtml = '';
        let countdownHtml = '';
        let btnHtml = btnElement.innerHTML;
        let btnClass = 'btn-take';

        // 根据不同状态显示不同内容
        if (now < examDate) {
            // 考试尚未开始，显示距离开始的倒计时
            timeDiff = examDate - now;
            statusHtml = '<span class="status-tag status-upcoming">即将开始</span>';
            countdownHtml = formatCountdown(timeDiff, '距离开始: ');
            btnClass = 'btn-take btn-disabled';
        } else if (now <= endDate) {
            // 考试进行中，显示距离结束的倒计时
            timeDiff = endDate - now;
            statusHtml = '<span class="status-tag status-exam">进行中</span>';
            countdownHtml = formatCountdown(timeDiff, '剩余时间: ');
            btnClass = 'btn-take';
        } else {
            // 考试已结束
            statusHtml = '<span class="status-tag status-finished">已结束</span>';
            countdownHtml = '考试已结束';
            btnClass = 'btn-take btn-disabled';
            btnHtml = '考试已结束';
        }

        // 更新DOM
        statusElement.innerHTML = statusHtml;
        countdownElement.innerHTML = countdownHtml;
        btnElement.className = btnClass;
        btnElement.innerHTML = btnHtml;
    }

    // 格式化倒计时显示
    function formatCountdown(millis, prefix = '') {
        const totalSeconds = Math.floor(millis / 1000);
        const hours = Math.floor(totalSeconds / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const seconds = totalSeconds % 60;

        let timeStr = '';
        if (hours > 0) {
            timeStr += `${hours}时`;
        }
        timeStr += `${minutes.toString().padStart(2, '0')}分`;
        timeStr += `${seconds.toString().padStart(2, '0')}秒`;

        return `${prefix}${timeStr}`;
    }
</script>
</body>
</html>